package com.wisezone.net.ex06_imserver;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 1. 创建ServerSocket实例，监听端口
 */
public class IMServer {
    private static final int TYPE_TEXT = 1;
    private static final int TYPE_PICTURE = 2;
    private static final int PORT = 9527;
    public Socket socket;

    /**
     * 启动sokcet服务端
     */
    public void startServer() {
        try {
            System.out.println("socket服务端启动...");
            ServerSocket serverSocket = new ServerSocket(PORT);
            socket = serverSocket.accept();
            System.out.println("socket连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 服务端接收图片
     */
    public void receivePicture() {
        File file = new File("./pic/serverpic.jpg");
        OutputStream os = null;
        try {
            InputStream in = socket.getInputStream(); //socket输入流
            os = new FileOutputStream(file); //文件输出流

            byte[] b = new byte[20]; //字节数组缓存
            int len = 0;
            while ((len = in.read(b)) != -1) {
                os.write(b, 0, len);
            }
        } catch (IOException e) {
//            e.printStackTrace();
            System.err.println("socket连接出错" + e);
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接收文本消息
     */
    public void receiveText() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = br.readLine();
            if (message != null)
                System.out.println(message);

        } catch (IOException e) {
//            e.printStackTrace();
            System.err.println("socket连接出错" + e);
        }
    }

    /**
     * 接收图片或文本
     */
    public void receiveMessage(){
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            while(true) {
                int type = dis.readInt();
                    System.out.println("type :"+type);
                    switch (type) {
                        case TYPE_TEXT:
                            receiveText();
                            break;
                    case TYPE_PICTURE:
                        receivePicture();
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        IMServer server = new IMServer();
        server.startServer();
        server.receiveMessage();

    }
}
